<template>
  <div class="user-management">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h2>用户管理</h2>
          <el-space>
            <el-button type="primary" @click="showCreateForm = true">
              <el-icon><Plus /></el-icon>
              新建用户
            </el-button>
            <el-button @click="refreshUsers">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </el-space>
        </div>
      </template>
      
      <div class="filters">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户姓名"
          @input="searchUsers"
          clearable
          style="max-width: 400px"
        >
          <template #prefix><el-icon><Search /></el-icon></template>
        </el-input>
      </div>
      
      <div class="table-container">
        <el-table 
          :data="users" 
          stripe
          border
          v-loading="loading"
          style="width: 100%; min-width: 800px"
        >
          <el-table-column prop="id" label="ID" width="130" />
          <el-table-column prop="username" label="用户名" width="100" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
          <el-table-column prop="fullName" label="姓名" width="120" show-overflow-tooltip />
          <el-table-column label="登录权限" width="90">
            <template #default="{ row }">
              <el-tag :type="row.canLogin ? 'success' : 'danger'" size="small">
                {{ row.canLogin ? '允许' : '禁止' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="管理员" width="80">
            <template #default="{ row }">
              <el-tag :type="row.isAdmin ? '' : 'info'" size="small">
                {{ row.isAdmin ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="160" show-overflow-tooltip>
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-space :size="4">
                <el-button type="info" link size="small" @click="viewUser(row)">
                  查看
                </el-button>
                <el-button type="warning" link size="small" @click="editUser(row)">
                  编辑
                </el-button>
                <el-dropdown @command="(command) => handleCommand(command, row)">
                  <el-button type="primary" link size="small">
                    更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="toggleLogin">
                        {{ row.canLogin ? '禁用登录' : '启用登录' }}
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="currentUser && currentUser.isAdmin && currentUser.id !== row.id"
                        command="toggleAdmin"
                      >
                        {{ row.isAdmin ? '取消管理员' : '设为管理员' }}
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="canDeleteUser(row)"
                        command="delete"
                        divided
                      >
                        <span style="color: #f56c6c">删除用户</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    
    <!-- 用户查看对话框 -->
    <el-dialog
      v-model="showViewDialog"
      title="用户详情"
      width="600px"
    >
      <div v-if="viewingUser">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="ID">{{ viewingUser.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ viewingUser.username }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ viewingUser.email }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ viewingUser.fullName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="登录权限">
            <el-tag :type="viewingUser.canLogin ? 'success' : 'danger'">
              {{ viewingUser.canLogin ? '允许' : '禁止' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="管理员">
            <el-tag :type="viewingUser.isAdmin ? '' : 'info'">
              {{ viewingUser.isAdmin ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(viewingUser.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(viewingUser.updatedAt) }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <el-button @click="showViewDialog = false">关闭</el-button>
        <el-button type="primary" @click="editFromView">编辑</el-button>
      </template>
    </el-dialog>
    
    <!-- 用户编辑/创建对话框 -->
    <el-dialog
      v-model="showCreateForm"
      :title="editingUser ? '编辑用户' : '新建用户'"
      width="600px"
    >
      <el-form
        :model="userForm"
        label-width="100px"
      >
        <el-form-item label="用户名" required>
          <el-input 
            v-model="userForm.username" 
            placeholder="请输入用户名"
            :disabled="!!editingUser"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" required>
          <el-input v-model="userForm.email" type="email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="姓名">
          <el-input v-model="userForm.fullName" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item v-if="!editingUser" label="密码" required>
          <el-input 
            v-model="userForm.password" 
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="登录权限">
          <el-switch 
            v-model="userForm.canLogin"
            active-text="允许"
            inactive-text="禁止"
          />
        </el-form-item>
        
        <el-form-item label="管理员">
          <el-switch 
            v-model="userForm.isAdmin"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="loading">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Plus, Refresh, Search, ArrowDown } from '@element-plus/icons-vue'
import { userAPI } from '@api/user.js'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'UserManagement',
  components: {
    Plus,
    Refresh,
    Search,
    ArrowDown
  },
  data() {
    return {
      users: [],
      allUsers: [],
      loading: false,
      searchKeyword: '',
      showCreateForm: false,
      showViewDialog: false,
      editingUser: null,
      viewingUser: null,
      userForm: {
        username: '',
        email: '',
        fullName: '',
        password: '',
        canLogin: true,
        isAdmin: false
      }
    }
  },
  computed: {
    currentUser() {
      return this.$store.state.user
    }
  },
  mounted() {
    this.loadUsers()
  },
  methods: {
    async loadUsers() {
      this.loading = true
      try {
        const response = await userAPI.getAllUsers()
        if (response.data.success) {
          this.users = response.data.data
          this.allUsers = response.data.data
        }
      } catch (error) {
        console.error('加载用户失败:', error)
        ElMessage.error('加载用户失败')
      } finally {
        this.loading = false
      }
    },
    
    refreshUsers() {
      this.searchKeyword = ''
      this.loadUsers()
    },
    
    searchUsers() {
      if (!this.searchKeyword.trim()) {
        this.users = this.allUsers
        return
      }
      
      const keyword = this.searchKeyword.toLowerCase()
      this.users = this.allUsers.filter(user => 
        (user.fullName && user.fullName.toLowerCase().includes(keyword)) ||
        user.username.toLowerCase().includes(keyword) ||
        user.email.toLowerCase().includes(keyword)
      )
    },
    
    viewUser(user) {
      console.log('查看用户:', user)
      this.viewingUser = user
      this.showViewDialog = true
    },
    
    editUser(user) {
      console.log('编辑用户:', user)
      this.editingUser = user
      this.userForm = {
        username: user.username,
        email: user.email,
        fullName: user.fullName || '',
        password: '',
        canLogin: user.canLogin,
        isAdmin: user.isAdmin
      }
      this.showCreateForm = true
    },
    
    editFromView() {
      this.editingUser = this.viewingUser
      this.userForm = {
        username: this.viewingUser.username,
        email: this.viewingUser.email,
        fullName: this.viewingUser.fullName || '',
        password: '',
        canLogin: this.viewingUser.canLogin,
        isAdmin: this.viewingUser.isAdmin
      }
      this.showViewDialog = false
      this.showCreateForm = true
    },
    
    async saveUser() {
      if (!this.userForm.username || !this.userForm.email) {
        ElMessage.warning('请填写用户名和邮箱')
        return
      }
      
      if (!this.editingUser && !this.userForm.password) {
        ElMessage.warning('请设置密码')
        return
      }
      
      this.loading = true
      
      try {
        if (this.editingUser) {
          const response = await userAPI.updateUser(this.editingUser.id, this.userForm)
          if (response.data.success) {
            ElMessage.success('更新成功')
            this.loadUsers()
            this.closeModal()
          }
        } else {
          const response = await userAPI.createUser(this.userForm)
          if (response.data.success) {
            ElMessage.success('创建成功')
            this.loadUsers()
            this.closeModal()
          }
        }
      } catch (error) {
        console.error('保存用户失败:', error)
        ElMessage.error('保存失败')
      } finally {
        this.loading = false
      }
    },
    
    async handleCommand(command, user) {
      if (command === 'toggleLogin') {
        await this.toggleLoginPermission(user)
      } else if (command === 'toggleAdmin') {
        await this.toggleAdminPermission(user)
      } else if (command === 'delete') {
        ElMessageBox.confirm('确定要删除这个用户吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteUser(user.id)
        }).catch(() => {})
      }
    },
    
    async toggleLoginPermission(user) {
      try {
        const response = await userAPI.updateUser(user.id, {
          ...user,
          canLogin: !user.canLogin
        })
        if (response.data.success) {
          ElMessage.success(user.canLogin ? '已禁用登录' : '已允许登录')
          this.loadUsers()
        }
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败')
      }
    },
    
    async toggleAdminPermission(user) {
      try {
        const response = await userAPI.updateUser(user.id, {
          ...user,
          isAdmin: !user.isAdmin
        })
        if (response.data.success) {
          ElMessage.success(user.isAdmin ? '已取消管理员权限' : '已设为管理员')
          this.loadUsers()
        }
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败')
      }
    },
    
    async deleteUser(id) {
      try {
        const response = await userAPI.deleteUser(id)
        if (response.data.success) {
          ElMessage.success('删除成功')
          this.loadUsers()
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        ElMessage.error('删除失败')
      }
    },
    
    closeModal() {
      this.showCreateForm = false
      this.editingUser = null
      this.userForm = {
        username: '',
        email: '',
        fullName: '',
        password: '',
        canLogin: true,
        isAdmin: false
      }
    },
    
    canDeleteUser(user) {
      return this.currentUser && 
             this.currentUser.isAdmin && 
             this.currentUser.id !== user.id
    },
    
    formatDate(dateString) {
      if (!dateString) return ''
      return new Date(dateString).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.filters {
  margin-bottom: 16px;
}

.table-container {
  overflow-x: auto;
  width: 100%;
}
</style>
